package org.opensuse.bs.ui.model;

import java.util.Vector;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.opensuse.bs.ui.BSUIPlugin;
import org.opensuse.bs.ui.OSC;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class RootElement extends BSModelElement {
	private int index;
	public RootElement(int i) {
		super("root", null);
		index = i;
	}
	
	public Object[] fetchChildren(Object object, IProgressMonitor monitor) {
		Vector<String> projs = new Vector<String>();
		if(index == 0) {
			try {
				Document doc = OSC.toXML("meta user "+BSUIPlugin.getDefault().getUser());
				if(doc != null) {
					NodeList watchList = doc.getElementsByTagName("watchlist");
					if(watchList.getLength() != 0) {
						NodeList prjList = ((Element) watchList.item(0)).getElementsByTagName("project");
						for(int i=0;i<prjList.getLength();i++) {
							Element one = (Element) prjList.item(i);
							projs.add(one.getAttribute("name"));
						}
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		else if(index == 1){
			projs = OSC.run("list");
		}
		else {
			Vector<String> aim = BSUIPlugin.getDefault().getAimed();
			if(!aim.isEmpty()) {
				for(String e : aim) {
					projs.add(e);
				}
			}
		}
		if(! projs.isEmpty()) {
			children = new RemoteProject[projs.size()];
			for(int i=0;i<projs.size();i++) {
				children[i] = new RemoteProject(projs.elementAt(i), this);
			}
			return children;
		}
		else
			return new Object[0];
	}
	
	public Object getAdapter(Class adapter) {
		if (adapter == IWorkbenchAdapter.class) return this;
		return null;
	}
	
	public ImageDescriptor getImageDescriptor(Object object) {
		return null;
	}
	
	public Object getParent(Object o) {
		return null;
	}
}
